package com.example.lostandfoundsystem.web.controllers.system.admin;

import com.example.lostandfoundsystem.models.system.Admin;
import com.example.lostandfoundsystem.models.system.Role;
import com.example.lostandfoundsystem.services.common.ResultService;
import com.example.lostandfoundsystem.services.system.AdminRolePermissionService;
import com.example.lostandfoundsystem.services.system.AdminService;
import gaarason.database.appointment.Paginate;
import gaarason.database.contract.eloquent.Builder;
import gaarason.database.contract.eloquent.Record;
import gaarason.database.exception.EntityNotFoundException;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author lucifer
 * @since 2024-07-12-15:23
 */
@RestController
@RequestMapping("/admin")
public class AdminController {
    @Resource
    Admin.Model adminModel;

    @Resource
    Role.Model roleModel;

    // 获取单个管理员信息
    @GetMapping("/item")
    ResultService.Result item(@RequestParam Map<String, String> params) {
        // 返回值
        ResultService.Result result = ResultService.getNormalResult();
        Record<Admin, Long> admin;
        if (Objects.isNull(params.get("id"))) {
            // 管理员不存在
            result.code = ResultService.NOT_FOUND;
            result.msg = "管理员不存在";
            return result;
        } else {
            try {
                admin = adminModel.newQuery().findOrFail(params.get("id"));
            } catch (EntityNotFoundException e) {
                // 找不到就报错
                result.code = ResultService.NOT_FOUND;
                result.msg = "管理员不存在";
                return result;
            }
            // 正常返回结果
            result.data = admin.getEntity();
        }
        return result;
    }

    // 获取所有管理员信息
    @GetMapping("/index")
    ResultService.Result index(@RequestParam Map<String, String> params) {
        // 分页单独处理
        String page = params.get("page");
        if (Objects.isNull(page)) {
            // 如果没有页数，默认为第一页
            page = "1";
        }
        // 生成查询器
        Builder<Admin, Long> builder = adminModel.newQuery();
        // 放入参数
        params.forEach((key, value) -> {
            if (!Objects.isNull(key) && !key.equals("page")) {
                // 要去掉page这个参数，如果还要去掉其他就直接在这里加
                if (!Objects.isNull(value)) {
                    builder.where(key, value);
                }
            }
        });

        // 返回结果,每页十五条记录
        Paginate<Admin> paginate = builder.paginate(page, 15);

        // 对结果进行处理
        Map<String, Object> data = new HashMap<>();
        data.put("currentPage", paginate.getCurrentPage());
        data.put("lastPage", paginate.getLastPage());
        data.put("total", paginate.getTotal());
        data.put("perPage", paginate.getPerPage());
        data.put("data", paginate.getItemList());
        ResultService.Result result = ResultService.getNormalResult();
        result.data = data;
        return result;
    }

    // 修改管理员列表
    @PostMapping("/change")
    ResultService.Result change(@RequestParam Map<String, String> params) {
        // 返回值
        ResultService.Result result = ResultService.getNormalResult();
        Record<Admin, Long> admin;
        if (Objects.isNull(params.get("id"))) {
            // 新建
            admin = adminModel.newRecord();
        } else {
            // 更新
            try {
                admin = adminModel.newQuery().findOrFail(params.get("id"));
            } catch (EntityNotFoundException e) {
                // 找不到就报错
                result.code = ResultService.NOT_FOUND;
                result.msg = "id not found";
                return result;
            }
        }
        // 填充对应参数
        admin.getEntity().setNumber(params.get("number"));
        admin.getEntity().setName(params.get("name"));
        admin.save();
        return result;
    }

    // 删除管理员列表
    @PostMapping("/delete")
    ResultService.Result delete(@RequestParam Map<String, String> params) {
        // 返回值
        ResultService.Result result = ResultService.getNormalResult();
        if (!Objects.isNull(params.get("id"))) {
            // 删除
            try {
                adminModel.newQuery().findOrFail(params.get("id")).delete();
            } catch (EntityNotFoundException e) {
                // 找不到就报错
                result.code = ResultService.NOT_FOUND;
                result.msg = "id not found";
                return result;
            }
        }
        return result;
    }

    @GetMapping("/getRole")
    ResultService.Result getRole(@RequestParam Map<String, String> params) {
        // 返回值
        ResultService.Result result = ResultService.getNormalResult();
        if (!Objects.isNull(params.get("id"))) {
            // 获得id，根据id查出管理员，根据管理员筛选出角色
            try {
                Record<Admin, Long> admin = adminModel.newQuery().findOrFail(params.get("id"));
                List<Map<String, String>> roleIdList = AdminService.getAdminRole(admin.getEntity());
                result.data = roleIdList;
            } catch (EntityNotFoundException e) {
                // 找不到就报错
                result.code = ResultService.NOT_FOUND;
                result.msg = "admin not found";
                return result;
            }
        } else {
            //找不到就报错
            result.code = ResultService.NOT_FOUND;
            result.msg = "id not found";
        }
        return result;
    }

    @GetMapping("/changeRole")
    ResultService.Result changeRole(@RequestParam Map<String, String> params) {
        // 返回值
        ResultService.Result result = ResultService.getNormalResult();
        if (Objects.isNull(params.get("id"))) {
            // 找不到就报错
            result.code = ResultService.NOT_FOUND;
            result.msg = "id not found";
            return result;
        } else if (Objects.isNull(params.get("role_id"))) {
            result.code = ResultService.NOT_FOUND;
            result.msg = "role_id not found";
            return result;
        } else if (Objects.isNull(params.get("checked"))) {
            result.code = ResultService.NOT_FOUND;
            result.msg = "checked not found";
            return result;
        }
        // 根据id修改对应权限，checked是0就是取消，checked不是0就是添加
        if (params.get("checked").equals("0")) {
            // checked是0，代表删除
            AdminRolePermissionService.deleteAdminRole(params.get("id"), params.get("role_id"));
        } else {
            // checked不是0，代表增加
            AdminRolePermissionService.insertAdminRole(params.get("id"), params.get("role_id"));
        }
        return result;
    }
}

